"""
This script is used to transform pdm package to poetry package.

"""
import pathlib


def main_trans():
    """读取文件;"""
    r = pathlib.Path("./require")
    res = r.read_text()
    p_list = res.split("\n")
    res_l = []
    for p in p_list:
        new_p = process_str(p)
        if new_p.endswith(","):
            new_p = new_p[:-1]
        res_l.append(new_p)

    res_new = "\n".join(res_l)
    with open("require-2", "w") as f:
        f.write(res_new)


def filter_neg(pack, ch, inx) -> int:
    res = pack.find(ch)
    if res == -1:
        return inx
    else:
        return min(res, inx)


def process_str(pack: str) -> str:
    inx = pack.find('"')
    pack = pack[inx + 1 :]

    # find first <,>,=
    inx = 200
    for ch in (">", "<", "=", "~", "^"):
        inx = filter_neg(pack, ch, inx)

    if inx == -1:
        raise Exception(f"should not be -1, {pack}")

    # back ="==test"
    pack = pack[:inx] + '="' + pack[inx:]
    pack = pack.replace("==", "")
    return pack


def test_process():
    """test in main.py"""

    def test_assert(pack, pack_equal):
        a = process_str(pack)
        assert a == pack_equal, a

    a = process_str('"black==1.2.2"')
    assert a == 'black="1.2.2"', a

    b = process_str('"black>=1.2,<1.3"')
    assert b == 'black=">=1.2,<1.3"', b

    c = process_str('"supply-entity~=0.1.2"')
    assert c == 'supply-entity="~=0.1.2"', c

    test_assert('"material-management-backend~=0.1.3"', 'material-management-backend="~=0.1.3"')


if __name__ == "__main__":
    test_process()
    main_trans()
